﻿using Db_Sqlite.DataAccess;
using Db_Sqlite.dataTables;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Db_Sqlite.Services
{

    public sealed class CsvProcessor
    {
        private readonly StockDatabaseAsync _repository;

        // 构造函数，用于初始化_repository字段
        public CsvProcessor(StockDatabaseAsync repository) =>
            _repository = repository;


        // 定义一个私有异步方法，用于处理单个文件
        public async Task ProcessSingleFileAsync(
            IEnumerable<string> filePaths)
        {
            foreach (var filePath in filePaths)
            {
                var dbs = new List<DtList>();
                // 逐行读取文件内容，这里使用了异步流
                await foreach (var line in File.ReadLinesAsync(filePath))
                {
                    var fields = SplitCsv(line);
                    if (fields[0] == "原始输入" || fields.Length<22) { // 跳过标题行
                        continue;
                    }
                    var dbRecord = new DtList(fields);
                    dbs.Add(dbRecord);
                }

                await _repository.BuckUpsertTradeDataAsync(dbs);
            }
               

        }

        // <summary>
        // 定义一个函数，用于拆分带有逗号分隔的CSV字符串
        // </summary>
        private static string[] SplitCsv(string input)
        {
            var result = new List<string>();
            bool inQuotes = false;
            var field = new StringBuilder();

            foreach (char c in input)
            {
                if (c == '"' && (field.Length == 0 || field[field.Length - 1] != '\\'))
                {
                    inQuotes = !inQuotes;
                }
                else if (c == ',' && !inQuotes)
                {
                    result.Add(field.ToString());
                    field.Clear();
                }
                else
                {
                    field.Append(c);
                }
            }
            result.Add(field.ToString());
            return result.ToArray();
        }
    }



}
